<template>
  <div class="ctr-box">
    <div class="row selecttype">
      <div class="label">广播方式</div>
      <el-select size="mini" v-model="broadcastType" placeholder="请选择广播方式">
        <el-option v-for="item in [{id:0,name:'TCP广播，不带包长'},{id:1,name:'TCP广播，带2字节包长'},{id:2,name:'UDP广播'}]"
          :key="item.id" :label="item.name" :value="item.id"></el-option>
      </el-select>
    </div>
    <div class="ctr1">
      <div class="row">
        <div class="col-lg-offset-2 col-lg-3 col-xs-4 col-md-4 divmd"
          @mousedown="setYdControl(1)" @mouseup="setYdUpControl(1)" @mouseenter="sventerorleave(1, 1)" @mouseleave="sventerorleave(1, 2)">
          <img class="ytbtnmenu" src="/static/image/yt/zs-01.png" v-show="zsflag" title="左上" />
          <img class="ytbtnmenu" src="/static/image/yt/zs-02.png" v-show="!zsflag" title="左上" />
        </div>
        <div
          class="col-lg-3 col-xs-4 col-md-4 divmd"
          @mousedown="setYdControl(2)"
          @mouseup="setYdUpControl(2)"
          @mouseenter="sventerorleave(2, 1)"
          @mouseleave="sventerorleave(2, 2)"
        >
          <img
            class="ytbtnmenu"
            src="/static/image/yt/s-01.png"
            v-show="sflag"
            title="上"
          />
          <img
            class="ytbtnmenu"
            src="/static/image/yt/s-02.png"
            v-show="!sflag"
            title="上"
          />
        </div>
        <div
          class="col-lg-offset-1 col-lg-3 col-xs-4 col-md-4 divmd"
          @mousedown="setYdControl(3)"
          @mouseup="setYdUpControl(3)"
          @mouseenter="sventerorleave(3, 1)"
          @mouseleave="sventerorleave(3, 2)"
        >
          <img
            class="ytbtnmenu"
            src="/static/image/yt/ys-01.png"
            v-show="ysflag"
            title="右上"
          />
          <img
            class="ytbtnmenu"
            src="/static/image/yt/ys-02.png"
            v-show="!ysflag"
            title="右上"
          />
        </div>
      </div>
      <div class="row">
        <div
          class="col-lg-offset-2 col-lg-3 col-xs-4 col-md-4 divmd"
          @mousedown="setYdControl(4)"
          @mouseup="setYdUpControl(4)"
          @mouseenter="sventerorleave(4, 1)"
          @mouseleave="sventerorleave(4, 2)"
        >
          <img
            class="ytbtnmenu"
            src="/static/image/yt/z-01.png"
            v-show="zflag"
            title="左"
          />
          <img
            class="ytbtnmenu"
            src="/static/image/yt/z-02.png"
            v-show="!zflag"
            title="左"
          />
        </div>
        <div class="col-lg-3 col-xs-4 col-md-4 divmd ctr-center">
          <i @mousedown="setYdControl(99)" @mouseup="setYdUpControl(99)" @mouseleave="setYdUpControl(99)" 
            :class="[talking?'fa-microphone':'fa-microphone-slash']" title="按住喊话" class="fa "></i>
        </div>
        <div
          class="col-lg-offset-1 col-lg-3 col-xs-4 col-md-4 divmd"
          @mousedown="setYdControl(6)"
          @mouseup="setYdUpControl(6)"
          @mouseenter="sventerorleave(6, 1)"
          @mouseleave="sventerorleave(6, 2)"
        >
          <img
            class="ytbtnmenu"
            src="/static/image/yt/y-01.png"
            v-show="yflag"
            title="右"
          />
          <img
            class="ytbtnmenu"
            src="/static/image/yt/y-02.png"
            v-show="!yflag"
            title="右"
          />
        </div>
      </div>
      <div class="row">
        <div
          class="col-lg-offset-2 col-lg-3 col-xs-4 col-md-4 divmd"
          @mousedown="setYdControl(7)"
          @mouseup="setYdUpControl(7)"
          @mouseenter="sventerorleave(7, 1)"
          @mouseleave="sventerorleave(7, 2)"
        >
          <img
            class="ytbtnmenu"
            src="/static/image/yt/zx-01.png"
            v-show="zxflag"
            title="左下"
          />
          <img
            class="ytbtnmenu"
            src="/static/image/yt/zx-02.png"
            v-show="!zxflag"
            title="左下"
          />
        </div>
        <div
          class="col-lg-3 col-xs-4 col-md-4 divmd"
          @mousedown="setYdControl(8)"
          @mouseup="setYdUpControl(8)"
          @mouseenter="sventerorleave(8, 1)"
          @mouseleave="sventerorleave(8, 2)"
        >
          <img
            class="ytbtnmenu"
            src="/static/image/yt/x-01.png"
            v-show="xflag"
            title="下"
          />
          <img
            class="ytbtnmenu"
            src="/static/image/yt/x-02.png"
            v-show="!xflag"
            title="下"
          />
        </div>
        <div
          class="col-lg-offset-1 col-lg-3 col-xs-4 col-md-4 divmd"
          @mousedown="setYdControl(9)"
          @mouseup="setYdUpControl(9)"
          @mouseenter="sventerorleave(9, 1)"
          @mouseleave="sventerorleave(9, 2)"
        >
          <img
            class="ytbtnmenu"
            src="/static/image/yt/yx-01.png"
            v-show="yxflag"
            title="右下"
          />
          <img
            class="ytbtnmenu"
            src="/static/image/yt/yx-02.png"
            v-show="!yxflag"
            title="右下"
          />
        </div>
      </div>
      <div class="row">
        <el-slider
          class="myslider"
          v-model="speed"
          :min="1"
          :max="255"
          :format-tooltip="formatydTooltip"
          label="移动速度"
          @change="changeydsp"
        ></el-slider>
      </div>
    </div>
    <div class="ctr2">
      <div class="row" style="margin-bottom: 25px;">
        <div class="ctr2-left">
          <div
            @click="setYdControl(10)"
            @mouseenter="sventerorleave(10, 1)"
            @mouseleave="sventerorleave(10, 2)"
          >
            <img
              src="/static/image/yt/f-01.png"
              v-show="fjflag"
              title="焦距变小"
            />
            <img
              src="/static/image/yt/f-02.png"
              v-show="!fjflag"
              title="焦距变小"
            />
          </div>
          <div
            @click="setYdControl(12)"
            @mouseenter="sventerorleave(12, 1)"
            @mouseleave="sventerorleave(12, 2)"
          >
            <img
              src="/static/image/yt/o-01.png"
              v-show="ojflag"
              title="光圈缩小"
            />
            <img
              src="/static/image/yt/o-02.png"
              v-show="!ojflag"
              title="光圈缩小"
            />
          </div>
        </div>
        <div class="ctr2-right">
          <div
            @click="setYdControl(11)"
            @mouseenter="sventerorleave(11, 1)"
            @mouseleave="sventerorleave(11, 2)"
          >
            <img
              src="/static/image/yt/f+01.png"
              v-show="fjjflag"
              title="焦距变大"
            />
            <img
              src="/static/image/yt/f+02.png"
              v-show="!fjjflag"
              title="焦距变大"
            />
          </div>
          <div
            @click="setYdControl(13)"
            @mouseenter="sventerorleave(13, 1)"
            @mouseleave="sventerorleave(13, 2)"
          >
            <img
              src="/static/image/yt/o+01.png"
              v-show="ojjflag"
              title="光圈变大"
            />
            <img
              src="/static/image/yt/o+02.png"
              v-show="!ojjflag"
              title="光圈变大"
            />
          </div>
        </div>
      </div>
      <div class="row">
        <el-slider
          class="myslider"
          v-model="bjspeed"
          :min="1"
          :max="15"
          :format-tooltip="formatbjTooltip"
          label="变焦速度"
          @change="showalter"
        ></el-slider>
      </div>
    </div>
    <div id="intercom-player"></div>
  </div>
</template>

<script>
import {Recorder} from './voiceconfig.js'
export default {
  name: "yuntai-ctr",
  props: {
    params: {
      type: Object,
      default: () => ({
        device: "",
        channel: "",
      }),
    },
  },
  data() {
    return {
      zsflag: false,
      sflag: false,
      ysflag: false,
      zflag: false,
      sxflag: false,
      yflag: false,
      yxflag: false,
      xflag: false,
      zxflag: false,
      fjflag: false,
      fjjflag: false,
      ojflag: false,
      ojjflag: false,
      dflag: false,
      ykflag: false,
      upflag: true,
      downflag: false,
      //valuesp: 128,
      speed: 128,
      //valuebjsp: 0,
      bjspeed: 7,
			broadcastType: 0,//0：TCP广播，不带包长；1：TCP广播，带2字节包长；2：UDP广播;
      record: null,//多媒体对象，用来处理音频
			mediaStream: null,//为了把标签栏上的红色远点去掉
      talking: false,//对讲
      player: null,
      talkStream: "",
      socket: null,
    };
  },
  mounted() {
    this.loadIntercom();
  },
  methods: {
    isMobile(){
      return false;
    },
    loadIntercom(){//推流实现引入
      const s1 = document.createElement('script');
      s1.type = 'text/JavaScript';
      s1.src = '/static/intercom/g711.js';
      document.body.appendChild(s1);
    },
    setYdControl(val) {//按钮点击
      if (!this.params.channel) {
        this.$message.warning("请先选中正在播放的视频窗口！");
        return;
      }
      var that = this;
      let command = "";
      let speed = that.speed;
      if (val == 1) {//左上
        command = "upleft";
        if (that.isMobile()) {
          that.zsflag = false;
        }
      } else if (val == 2) {//上
        command = "up";
        if (that.isMobile()) {
          that.sflag = false;
        }
      } else if (val == 3) {//右上
        command = "upright";
        if (that.isMobile()) {
          that.ysflag = false;
        }
      } else if (val == 4) {//左
        command = "left";
        if (that.isMobile()) {
          that.zflag = false;
        }
      } else if (val == 6) {//右
        command = "right";
        if (that.isMobile()) {
          that.yflag = false;
        }
      } else if (val == 7) {//左下
        command = "downleft";
        if (that.isMobile()) {
          that.zxflag = false;
        }
      } else if (val == 8) {//下
        command = "down";
        if (that.isMobile()) {
          that.xflag = false;
        }
      } else if (val == 9) {//右下
        command = "downright";
        if (that.isMobile()) {
          that.yxflag = false;
        }
      } else if (val == 10) {//焦距变小
        command = "near";
        speed = that.bjspeed;
        if (that.isMobile()) {
          that.fjflag = false;
        }
      } else if (val == 11) {//焦距变大
        command = "far";
        speed = that.bjspeed;
        if (that.isMobile()) {
          that.fjjflag = false;
        }
      } else if (val == 12) {//光圈缩小
        command = "out";
        speed = that.bjspeed;
        if (that.isMobile()) {
          that.ojflag = false;
        }
      } else if (val == 13) {//光圈缩大
        command = "in";
        speed = that.bjspeed;
        if (that.isMobile()) {
          that.ojjflag = false;
        }
      }else if (val == 99) {//对讲
        that.talking = true;
      }
      if(val!=99){
        that.$http.postData("/ptz/control", {
          device: that.params.device,
          channel: that.params.channel,
          command: command,
          speed: speed
        }).then((ret) => {}).catch(() => {});
      }else{
        that.toPlayTalkChanel();
      }
    },
    toPlayTalkChanel(){//开启对讲0
      let that = this;
			navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia;
			if (!navigator.getUserMedia) {
        that.$message({
          type: 'warning',
          message: "浏览器不支持音频输入"
        });
			} else {
				navigator.getUserMedia({audio: true},
					function (mediaStream) {
            that.record = new Recorder(mediaStream);
						that.mediaStream = mediaStream;
						console.log('开始对讲');
            that.playTalkChanel();
					},
					function (error) {
						console.log(error);
						switch (error.message || error.name) {
							case 'PERMISSION_DENIED':
							case 'PermissionDeniedError':
								console.info('用户拒绝提供信息。');
								break;
							case 'NOT_SUPPORTED_ERROR':
							case 'NotSupportedError':
								console.info('浏览器不支持硬件设备。');
								break;
							case 'MANDATORY_UNSATISFIED_ERROR':
							case 'MandatoryUnsatisfiedError':
								console.info('无法发现指定的硬件设备。');
								break;
							default:
								console.info('无法打开麦克风。异常信息:' + (error.code || error.name));
								break;
						}
					}
				);
			}
    },
    initPlayer(id){
      if(!!this.player){
        this.player.destroy();
      }
      this.player = new JessibucaPro({
				container: document.getElementById(id),
				decoder: "/static/jessibuca/decoder-pro.js",
        isFlv: true,
				videoBuffer: 0.2, // 缓存时长
				hasVideo: false,//是否有视频，如果设置`false`，则不对视频数据解码，只播放音频数据。
				forceNoOffscreen: false,
				isNotMute: true
			});
			this.player.on("error", function (error) {
				console.log('error:', error)
			});
    },
    playTalkChanel(){//开启对讲1
      let that = this;
      that.initPlayer("intercom-player");
      that.$http.postData("/live/speak",{device: that.params.device}).then(function(res){
        if(!res.code){
          if(!!res.push){
            that.talkStream = res.stream;
            let playUrl = res.pull.WebSocket;
            if(location.protocol==='https:'){
              playUrl = res.pull.WebSockets;
            }
            console.log("对讲播放地址",playUrl);
            that.player.play(playUrl);
            that.useWebSocket(res.push.WebSockets);
          }
        }
      }).catch(function(err){
        console.log(err);
      });
    },
    useWebSocket(socketUrl) {
			let that =this;
      if(!socketUrl)return;
      //实现化WebSocket对象，指定要连接的服务器地址与端口  建立连接
      console.log("您的浏览器支持WebSocket",socketUrl);
      if (that.socket != null) {
        that.socket.close();
        that.socket = null;
      }
      that.socket = new WebSocket(socketUrl);
      that.socket.binaryType = 'arraybuffer'
      //打开事件
      that.socket.onopen = function () {
        console.log("websocket已打开");
        if (that.socket.readyState == 1) { //ws进入连接状态，则每隔500毫秒发送一包数据
          that.record.start(that.socket);
          that.playListenChanel();
        }
      };
      //获得消息事件
      that.socket.onmessage = function (msg) {
        var serverMsg = "收到服务端信息：" + msg.data;
        console.log(serverMsg);
      };
      //关闭事件
      that.socket.onclose = function () {
        that.record.clear();
        that.record.stop();
        console.log("websocket已关闭");
      };
      //发生了错误事件
      that.socket.onerror = function () {
        that.record.clear();
        that.record.stop();
        console.log("websocket发生了错误");
      }
		},
    playListenChanel(){//开启对讲2--广播
      let that = this;
      let obj = {
        'device': that.params.device,
        'channel': that.params.channel,
        'source': that.talkStream,
        'mode':that.broadcastType,//0：TCP广播，不带包长；1：TCP广播，带2字节包长；2：UDP广播;
      }
      that.$http.postData("/live/broadcast",obj).then(function(res){
        if(!res.code){}
      }).catch(function(err){
        console.log(err);
      });
    },
    setYdUpControl(val) {//按钮松开
      if (!this.params.channel) {
        return;
      }
      var that = this;
      this.talking = false;
      if(val!=99){
        that.$http.postData("/ptz/control", {
          device: that.params.device,
          channel: that.params.channel,
          command: 'stop',
        }).then((ret) => {}).catch(() => {});
      }else{
        that.stopTalkChanel();
      }
    },
    stopTalkChanel(){//停止对讲
      let that = this;
      if (that.socket) {
				that.socket.close();
				that.mediaStream.getTracks().forEach(track => track.stop());//为了把标签栏上的红色远点去掉
				that.socket = null;
			}
      if(that.record){
				that.record.clear();
				that.record.stop();
      }
      if(that.player){
        that.player.destroy();
        that.player = null;
      }
      if(that.talkStream){
        that.$http.postData("/live/broadcast_stop",{id: that.talkStream}).then(function(res){
          if(!res.code){}
        }).catch(function(err){
          console.error("catchcatchcatchcatch",err);
        });
        that.talkStream = "";
      }
			console.log('关闭对讲以及WebSocket');
    },
    sventerorleave(val, type) {
      //按钮点击
      var that = this;
      if (val == 1) {
        if (type == 1) {
          that.zsflag = true;
        } else {
          that.zsflag = false;
        }
      } else if (val == 2) {
        if (type == 1) {
          that.sflag = true;
        } else {
          that.sflag = false;
        }
      } else if (val == 3) {
        if (type == 1) {
          that.ysflag = true;
        } else {
          that.ysflag = false;
        }
      } else if (val == 4) {
        if (type == 1) {
          that.zflag = true;
        } else {
          that.zflag = false;
        }
      } else if (val == 5) {
        if (type == 1) {
          that.sxflag = true;
        } else {
          that.sxflag = false;
        }
      } else if (val == 6) {
        if (type == 1) {
          that.yflag = true;
        } else {
          that.yflag = false;
        }
      } else if (val == 7) {
        if (type == 1) {
          that.zxflag = true;
        } else {
          that.zxflag = false;
        }
      } else if (val == 8) {
        if (type == 1) {
          that.xflag = true;
        } else {
          that.xflag = false;
        }
      } else if (val == 9) {
        if (type == 1) {
          that.yxflag = true;
        } else {
          that.yxflag = false;
        }
      } else if (val == 10) {
        if (type == 1) {
          that.fjflag = true;
        } else {
          that.fjflag = false;
        }
      } else if (val == 11) {
        if (type == 1) {
          that.fjjflag = true;
        } else {
          that.fjjflag = false;
        }
      } else if (val == 12) {
        if (type == 1) {
          that.ojflag = true;
        } else {
          that.ojflag = false;
        }
      } else if (val == 13) {
        if (type == 1) {
          that.ojjflag = true;
        } else {
          that.ojjflag = false;
        }
      }else if (val == 16) {
        if (type == 1) {
          that.dflag = true;
        } else {
          that.dflag = false;
        }
      } else if (val == 17) {
        if (type == 1) {
          that.ykflag = true;
        } else {
          that.ykflag = false;
        }
      } else if (val == 99) {
        that.ykflag = false;
      }
    },
    formatydTooltip(val) {
      return "移动速度为" + val;
    },
    changeydsp(val) {
      //移动速度变化
      this.speed = val;
      if (!this.params.device) {
        this.$message.warning("请先选中正在播放的视频窗口！");
        return;
      }
      this.setYdControl(0);
    },
    formatbjTooltip(val) {
      return "变焦速度为" + val;
    },
    showalter(val) {
      if (!this.params.device) {
        this.$message.warning("请先选中正在播放的视频窗口！");
        return;
      }
    },
  },
};
</script>
<style lang="scss" scoped>
#intercom-player{
  width: 0;
  height: 0;
  padding: 0;
  position: absolute;
}
.ctr-box {
  position: relative;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  padding: 20px 20px 0;
  box-sizing: border-box;
  border-top: 1px solid #f3f4f5;
  background: #fff;
  .fa-times-circle {
    position: absolute;
    top: -17px;
    right: -2px;
    font-size: 20px;
    color: #6c7489;
  }
}
.ytbtnmenu {
  width: 100%;
  height: 30px;
}
.divmd {
  margin: 0;
  padding: 0;
  width: 35px;
  height: 30px;
  position: relative;
  overflow: hidden;
}
.ctr-box > div {
  display: block;
}
.ctr-box .selecttype{
  width: 100%;
  padding-bottom: 10px;
  display: flex;
  align-items: center;
  font-size: 13px;
  color: #333;
  .label{
    white-space: nowrap;
    margin-right: 5px;
  }
  >>>.el-select{
    .el-input__inner{
      padding-left: 8px;
    }
  }
}
.ctr1 {
  width: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  .ctr-center{
    font-size: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #6c7489;
    cursor: pointer;
    &:hover{
      color: rgb(11, 131, 220);
    }
    .fa-microphone{
      color: rgb(11, 131, 220);
    }
  }
}
.ctr1 .row {
  margin-left: 0;
  margin-right: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}
.ctr2 {
  width: 40%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
}
.ctr2 .row {
  margin-left: 0;
  margin-right: 0;
  width: 100%;
  margin: auto;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.ctr2-left > div,
.ctr2-right > div {
  display: block;
  margin-bottom: 4px;
}
.ctr2-left > div:last-child,
.ctr2-right > div:last-child {
  margin-bottom: 0;
}
.myslider {
  width: 105px;
}
.divmd img {
  width: 35px;
  height: 30px;
  cursor: pointer;
}
.ctr2 img {
  width: 39px;
  height: 27px;
  cursor: pointer;
}
</style>
